<template>
  <div class="table-box">
    <ProTable ref="proTableRef" row-key="id" :indent="20" :columns="columns" :request-api="fetchArticleCategoryTrees">
      <template #tableHeader>
        <el-button type="primary" v-auth="'Article.Category.AddCategory'" @click="open">新增文章分类</el-button>
      </template>
    </ProTable>
    <Edit ref="editRef" @success="refresh"></Edit>
  </div>
</template>

<script lang="tsx" setup>
import ProTable from "@/components/ProTable/index.vue";
import { fetchArticleCategoryTrees, removeArticleCategory } from "@/api/modules/article_category";
import { ColumnProps, ProTableInstance } from "@/components/ProTable/interface";
import Edit from "./components/edit.vue";
import { ref } from "vue";
import { RefOpenEventProps } from "@/typings/interface";
import { ArticleCategorySchema } from "@/schema";
import { ResultEnum } from "@/enums/httpEnum";
import { ElMessageBox, ElNotification } from "element-plus";

const editRef = ref<RefOpenEventProps<ArticleCategorySchema>>();
const proTableRef = ref<ProTableInstance>();

function open() {
  editRef.value?.open();
}

function edit(row) {
  editRef.value?.open(row);
}

function refresh() {
  proTableRef.value?.getTableList();
}

function remove(row) {
  ElMessageBox.confirm("提示", { type: "error", message: "是否删除当前数据？" })
    .then(() => {
      if (row?.id) {
        removeArticleCategory({ id: row.id }).then(r => {
          const { code, message } = r;
          if (code == ResultEnum.SUCCESS) {
            ElNotification.success("删除成功！");
            refresh();
          } else {
            ElNotification.error(message);
          }
        });
      }
    })
    .catch(err => {
      console.error(err);
    });
}

const columns: ColumnProps[] = [
  { type: "index", label: "序号", fixed: "left", width: 80 },
  { prop: "categoryName", label: "文章分类名称", align: "left", headerAlign: "left" },
  { prop: "categoryCode", label: "文章分类编码" },
  {
    prop: "action",
    label: "操作",
    fixed: "right",
    render: ({ row }) => {
      return (
        <>
          <el-button type="primary" v-auth="Article.Category.EditCategory" link onClick={() => edit(row)}>
            编辑
          </el-button>
          <el-button type="danger" v-auth="Article.Category.RemoveCategory" link onClick={() => remove(row)}>
            删除
          </el-button>
        </>
      );
    }
  }
];
</script>
